define(function(require, exports){
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var $ = require('jquery');
	var util = require('util');
	var dialog = require('@base/dialog').base;

	var AdImport = view.widget.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'listUrl': 'spot/listByPIds',
				'layout': {
					"module": dialog,
					"title": LANG('导入广告位'),
					"silence": false,
					"buttonConfig": {
						"ok": {
							"value": LANG('确定')
						}
					},
					'size': 'm'
				},
				'view_model': {
					// 媒体广告位ID
					mediaIds: ''
				}
			});

			this.Super('init', arguments);
		}
		,afterBuild: function(){
			var self = this;
			var el = self.getDOM();

			el.append($([
				'<div class="M-formConGroup">',
					'<label class="group-label">' + LANG('渠道：') + '</label>',
					'<div class="group-content">',
						'<div pub-name="channelDrop" pub-mod="@base/common/drop.drop"/>',
					'</div>',
				'</div>',
				'<div class="M-formConGroup">',
					'<label class="group-label">' + LANG('媒体广告位ID：') + '</label>',
					'<div class="group-content">',
						'<textarea ms-duplex="mediaIds" rows="10" cols="70" placeholder="'+ LANG('请输入媒体广告位ID，多个ID请用回车键换行隔开') +'"/>',
					'</div>',
				'</div>'
			].join('')));

			self.buildFromTemplate({
				channelDrop: {
					'def': LANG('请选择'),
					'options': pubjs.config('exchange'),
					'panel_config': {
						'height': 200
					}
				}
			});
		}
		,getValue: function(){
			var vm = this.vm.$;
			var cs = this.$;
			var MediaIds = [];
			var value = vm.mediaIds.split('\n');
			value.forEach(function(item){
				var trimItem = util.trim(item);
				if (trimItem) {
					MediaIds.push(trimItem);
				}
			});

			var result = {
				'ChannelId': cs.channelDrop.getValue('id'),
				'ids': MediaIds.join(',')
			};

			return result;
		}
		,setValue: function(data){
			var vm = this.vm.$;
			var cs = this.$;
			cs.channelDrop.setValue(data.ChannelId);
			vm.mediaIds = data.ids.join('\n') || '';

			return this;
		}
		,reset: function(){
			var cs = this.$;
			this.vm.reset();
			cs.channelDrop.reset();

			return this;
		}
		,validate: function(data){
			if (!data.ChannelId) {
				pubjs.alert(LANG('请选择渠道！'));
				return false;
			}
			if (!data.ids.length) {
				pubjs.alert(LANG('请输入媒体广告位ID！'));
				return false;
			}

			return true;
		}
		,onDialogOk: function(){
			var self = this;
			var data = self.getValue();
			var listUrl = this.getConfig('listUrl');
			if (self.validate(data)) {
				pubjs.loading.show();
				pubjs.mc.send(listUrl, data, self.afterSave.bind(self));
			}

			return false;
		}
		,afterSave: function(err, data){
			pubjs.loading.hide();
			if (err) {
				pubjs.alert(err.message);
				return false;
			}
			if(data && data.total == 0) {
				return pubjs.alert(LANG("导入的广告位失败，请检查相应渠道ID是否正确"))
			}
			
			this.fire('adImportOk', data);
			this.hide();
		}
	});

	exports.adImport = AdImport;
});